package com.zhome.gateway.filter.post;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.dto.RequestInfo;
import com.zhome.gateway.enums.FilterEnum;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.filter.AbstractZhomeZuulFilter;
import com.zhome.gateway.mq.RocketMQProducer;
import com.zhome.gateway.response.GatewayResponse;
import com.zhome.gateway.util.DesEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jcajce.provider.asymmetric.util.DESUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 *
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class ResponseWrapperFilter extends AbstractZhomeZuulFilter {

    private static final String TOPIC = "monitor";
    
    @Autowired
    private RocketMQProducer rocketMQProducer;

    @Override
    public String filterType() {
        return Constants.POST_KEY;
    }

    @Override
    public int filterOrder() {
        return FilterEnum.ResponseWrapperFilterEnum.getFilterOrder();
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        sendRequestInfo(ctx);
        try {
            String responseData = StreamUtils.copyToString(ctx.getResponseDataStream(), StandardCharsets.UTF_8);
            String message = gatewayResponseEncrypt(GateWayCodeEnum.CODE_SUCCESS, responseData);
            ctx.setResponseBody(message);
        } catch (Exception e) {
            log.error("requestId:%s", requestId(), e);
            setFailResponse(GateWayCodeEnum.INNER_ERROR);
        }
        return null;
    }

    public void sendRequestInfo(RequestContext ctx) {
        try {
            String serverName = String.valueOf(ctx.get(Constants.RequestContextKey.CTX_X_SERVER_NAME));
            String actionName = String.valueOf(ctx.get(FilterConstants.REQUEST_URI_KEY));
            Long startTime = (Long)ctx.get(Constants.RequestContextKey.CTX_X_REQ_START_TIME);
            if (startTime != null) {
                long timeConsume = System.currentTimeMillis() - startTime.longValue();
                
                RequestInfo requestInfo = RequestInfo.builder()
                        .serverName(serverName)
                        .path(actionName)
                        .startTime(startTime)
                        .timeConsume(timeConsume)
                        .endTime(System.currentTimeMillis())
                        .build();
                String  message = JSON.toJSONString(requestInfo);
                rocketMQProducer.sendMessage(TOPIC, message);
            }
        } catch (Exception e) {
            log.error("");
        }

    }



}
